<?php

namespace common\components\easy_wechat;

use Psr\SimpleCache\CacheInterface;

class Cache implements CacheInterface
{
    /**
     * @param string $key
     * @param mixed|null $default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        return \Yii::$app->cache->get($key) ?: $default;
    }

    /**
     * @param string $key
     * @param mixed $value
     * @param \DateInterval|int|null $ttl
     * @return bool
     */
    public function set($key, $value, $ttl = null)
    {
        return \Yii::$app->cache->set($key, $value, $ttl);
    }

    /**
     * @param string $key
     * @return bool
     */
    public function delete($key)
    {
        return \Yii::$app->cache->delete($key);
    }

    /**
     * @return bool
     */
    public function clear()
    {
        return \Yii::$app->cache->flush();
    }

    /**
     * @param iterable $keys
     * @param mixed|null $default
     * @return iterable
     */
    public function getMultiple($keys, $default = null)
    {
        $results = [];
        foreach ($keys as $k => $v) {
            $results[$v] = \Yii::$app->cache->get($v) ?: $default;
        }
        return $results;
        // TODO: Implement getMultiple() method.
    }

    /**
     * @param iterable $values
     * @param \DateInterval|int|null $ttl
     * @return bool
     */
    public function setMultiple($values, $ttl = null)
    {
        foreach ($values as $k => $v) {
            $this->set($k, $v, $ttl);
        }

        return true;
    }

    /**
     * @param iterable $keys
     * @return bool
     */
    public function deleteMultiple($keys)
    {
        foreach ($keys as $k => $v) {
            $this->delete($v);
        }
        return true;
    }

    /**
     * @param string $key
     * @return bool
     */
    public function has($key)
    {
        return \Yii::$app->cache->exists($key);
    }
}